package com.pet.jwt;

import com.alibaba.fastjson.JSON;


import com.pet.utils.JwtHelper;
import com.pet.utils.ResponseUtil;
import com.pet.utils.Result;
import com.pet.utils.ResultCodeEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JwtFilter extends GenericFilterBean {
    private RedisTemplate redisTemplate;

    public JwtFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        HttpServletRequest req = (HttpServletRequest) request;
        logger.info(req.getRequestURI());
        if ("/lovePet/system/index/login".equals(req.getRequestURI())
                || "/lovePet/system/index/register".equals(req.getRequestURI())
                || req.getRequestURI().contains("/lovePet/system/sysDoctor/findDataById")
                || "/lovePet/system/sysDoctor/findAll".equals(req.getRequestURI())
                || "/lovePet/system/index/checkCode".equals(req.getRequestURI())
                || "/lovePet/system/upload/uploadImage".equals(req.getRequestURI())
                || "/lovePet/system/upload/uploadVideo".equals(req.getRequestURI())) {
            chain.doFilter(req, response);
            return;
        }
        String jwtToken = req.getHeader("token");
        if (!StringUtils.isEmpty(jwtToken)) {
//            Claims claims = Jwts.parser().setSigningKey("wgh@123").parseClaimsJws(jwtToken.replace("Bearer", "")).getBody();
//            String username = claims.getSubject();
//            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));
            String username = JwtHelper.getUsername(jwtToken);
            String authoritiesString = (String) redisTemplate.opsForValue().get(username);
            List<Map> mapList = JSON.parseArray(authoritiesString, Map.class);
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (Map map : mapList) {
                authorities.add(new SimpleGrantedAuthority((String) map.get("authority")));
            }
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, authorities);
            SecurityContextHolder.getContext().setAuthentication(token);
            chain.doFilter(req, response);
        } else {
            ResponseUtil.out((HttpServletResponse) response, Result.build(null, ResultCodeEnum.PERMISSION));
        }
    }
}
